// 存储缓存相关代码
import Cookies from 'js-cookie'
import { randomChar, getTodayStr } from './tools.js'
import { freeReqNum } from './config.js'
import { isLogin } from './tools.js'
// import { useRoute } from 'vue-route'

// 限制次数
// cookie24小时，并不是凌晨12点过期，如果在过期前又访问了网站，cookie又会被重置，导致cookie永远无法过期。因此解决办法是在cookie的name上加上日期时间戳。过了12点，之前的cookie就丢弃不用

// 没有登录的用户使用限制，每天可以免费用1次，但是不能下载


const numsLimitKey = 'nums'

function getCookieName(){
  const route = useRoute()
  // console.log('route:', route)
  let routeName = route.name
  // let cookieName = routeName + '/' + numsLimitKey + '/' + getTodayStr()
  let cookieName = routeName + '/' + numsLimitKey
  // let cookieName = routeName + numsLimitKey
  return cookieName
}
function strToNumber(str) {
  if (str) {
    return parseInt(str) || 0;
  }
  return 0;
}
// 获取此时address请求的次数
function getCurUseNum() {
  // console.log('getCurUseNum')
  let cookieName = getCookieName()
  let valueStr = Cookies.get(cookieName) || sessionStorage.getItem(cookieName) || '0'
  let reqNum = strToNumber(valueStr);
  return reqNum
}

function setCurResNum(value = 0) {
  let cookieName = getCookieName()
  let tValue = value + randomChar();
  Cookies.set(cookieName, tValue, { expires: 1 });
  sessionStorage.setItem(cookieName, tValue);
}



export function isReqOverflow() {
  // 已经登录的用户不限量
  console.log('isLogin:',isLogin())
  if(isLogin()){
    return false
  }else {
    let times = getCurUseNum()
    // console.log('times:', times)
    setCurResNum(times + 1)


    return times > freeReqNum
  }
  
}


